#!/bin/python
import time
import re
import cv2
import easyocr


reader = easyocr.Reader(['en'])
comp=re.compile('^[~<>*]?([-]?\d+(\.\d)?).*$')

class FLIRError(Exception):
    def __init__(self, *args):
        self.args = args

class FLIR_Temp:
    def __init__(self, cam_id=None):
        if cam_id is None:
            for cam_id in range(10):
                self.cap = cv2.VideoCapture(cam_id)
                try:
                    temp = self.read()
                except FLIRError as e:
                    pass
                else:
                    print(f'found FLIR cam_id={cam_id}, temp={temp[1]}oC')
                    break
            else:
                raise FLIRError('find FLIR cam faild')
        else:
            self.cap = cv2.VideoCapture(cam_id)

    def read(self):
        ref, frame = self.cap.read()
        ts = time.time()
        if frame is None:
            raise FLIRError("can't read image")
        frame = frame[4:25, 32:95]
        result = reader.readtext(frame)
        if len(result) == 0:
            raise FLIRError("can't ocr text")
        s = result[0][1]
        m = comp.match(s)
        if m is None:
            raise FLIRError(f"can't re match '{s}'")
        return ts, float(m.group(1))

# demo
if __name__ == '__main__':
    flir = FLIR_Temp()
    while True:
        try:
            tmp = flir.read_tmp()
        except ValueError as e:
            print(e)
        else:
            print(tmp)

